"""
报告生成器
生成合同审核报告
"""

import json
from datetime import datetime
from typing import Dict, Any, List
from pathlib import Path

from config import Config

class ReportGenerator:
    """报告生成器类"""
    
    def __init__(self):
        """初始化报告生成器"""
        self.config = Config()
    
    def generate_report(self, filename: str, analysis_result: Dict[str, Any]) -> str:
        """
        生成审核报告
        
        Args:
            filename: 原始文件名
            analysis_result: 分析结果
            
        Returns:
            Markdown格式的报告内容
        """
        # 准备报告数据
        report_data = self._prepare_report_data(filename, analysis_result)
        
        # 使用模板生成报告
        report_content = self.config.REPORT_TEMPLATE.format(**report_data)
        
        # 保存报告到文件
        report_filename = self._save_report(filename, report_content)
        
        return report_content
    
    def _prepare_report_data(self, filename: str, analysis_result: Dict[str, Any]) -> Dict[str, str]:
        """
        准备报告数据
        
        Args:
            filename: 文件名
            analysis_result: 分析结果
            
        Returns:
            格式化的报告数据
        """
        # 基本信息
        overall_score = analysis_result.get('overall_score', 0)
        review_types = list(analysis_result.get('details', {}).keys())
        
        # 生成摘要
        summary = self._generate_summary(analysis_result)
        
        # 生成详细分析
        detailed_analysis = self._generate_detailed_analysis(analysis_result.get('details', {}))
        
        # 格式化风险
        risks = self._format_risks(analysis_result.get('risks', []))
        
        # 格式化建议
        recommendations = self._format_recommendations(analysis_result.get('recommendations', []))
        
        return {
            'filename': filename,
            'review_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'review_types': ', '.join(review_types),
            'overall_score': overall_score,
            'summary': summary,
            'detailed_analysis': detailed_analysis,
            'risks': risks,
            'recommendations': recommendations
        }
    
    def _generate_summary(self, analysis_result: Dict[str, Any]) -> str:
        """生成审核摘要"""
        overall_score = analysis_result.get('overall_score', 0)
        risk_count = len(analysis_result.get('risks', []))
        recommendation_count = len(analysis_result.get('recommendations', []))
        
        # 确定风险等级
        if overall_score >= 80:
            risk_level = "低风险"
            risk_emoji = "🟢"
        elif overall_score >= 60:
            risk_level = "中等风险"
            risk_emoji = "🟡"
        else:
            risk_level = "高风险"
            risk_emoji = "🔴"
        
        summary = f"""
{risk_emoji} **风险等级**: {risk_level}

📊 **关键指标**:
- 总体评分: {overall_score}/100
- 发现风险项: {risk_count}个
- 改进建议: {recommendation_count}个

💡 **总体评价**: 
"""
        
        if overall_score >= 80:
            summary += "该合同整体风险较低，条款相对完善，建议在专业律师指导下签署。"
        elif overall_score >= 60:
            summary += "该合同存在一定风险，建议仔细审查相关条款并考虑修改后再签署。"
        else:
            summary += "该合同存在较高风险，强烈建议在专业律师协助下进行重大修改后再考虑签署。"
        
        return summary
    
    def _generate_detailed_analysis(self, details: Dict[str, Any]) -> str:
        """生成详细分析内容"""
        if not details:
            return "暂无详细分析数据。"
        
        analysis_content = ""
        
        for review_type, result in details.items():
            analysis_content += f"\n### {review_type}\n\n"
            
            if isinstance(result, dict):
                # 评分
                if 'score' in result:
                    score = result['score']
                    analysis_content += f"**评分**: {score}/100\n\n"
                
                # 详细内容
                if 'details' in result:
                    analysis_content += f"**分析详情**:\n{result['details']}\n\n"
                
                # 特定风险
                if 'risks' in result and result['risks']:
                    analysis_content += "**发现的问题**:\n"
                    for risk in result['risks']:
                        analysis_content += f"- {risk}\n"
                    analysis_content += "\n"
                
                # 特定建议
                if 'recommendations' in result and result['recommendations']:
                    analysis_content += "**改进建议**:\n"
                    for rec in result['recommendations']:
                        analysis_content += f"- {rec}\n"
                    analysis_content += "\n"
                
                # 错误信息
                if 'error' in result:
                    analysis_content += f"⚠️ **处理错误**: {result['error']}\n\n"
            
            else:
                analysis_content += f"{result}\n\n"
        
        return analysis_content
    
    def _format_risks(self, risks: List[str]) -> str:
        """格式化风险列表"""
        if not risks:
            return "✅ 未发现明显风险项目。"
        
        formatted_risks = ""
        for i, risk in enumerate(risks, 1):
            formatted_risks += f"{i}. ⚠️ {risk}\n"
        
        return formatted_risks
    
    def _format_recommendations(self, recommendations: List[str]) -> str:
        """格式化建议列表"""
        if not recommendations:
            return "暂无特定改进建议。"
        
        formatted_recommendations = ""
        for i, rec in enumerate(recommendations, 1):
            formatted_recommendations += f"{i}. 💡 {rec}\n"
        
        return formatted_recommendations
    
    def _save_report(self, original_filename: str, report_content: str) -> str:
        """
        保存报告到文件
        
        Args:
            original_filename: 原始文件名
            report_content: 报告内容
            
        Returns:
            报告文件路径
        """
        # 生成报告文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        base_name = Path(original_filename).stem
        report_filename = f"contract_review_{base_name}_{timestamp}.md"
        
        # 保存到reports目录
        report_path = self.config.REPORTS_DIR / report_filename
        
        try:
            with open(report_path, 'w', encoding='utf-8') as f:
                f.write(report_content)
            
            return str(report_path)
            
        except Exception as e:
            # 如果保存失败，返回临时路径
            return f"报告生成成功，但保存失败: {e}"
    
    def generate_json_report(self, filename: str, analysis_result: Dict[str, Any]) -> str:
        """
        生成JSON格式的报告
        
        Args:
            filename: 文件名
            analysis_result: 分析结果
            
        Returns:
            JSON格式的报告
        """
        report_data = {
            "filename": filename,
            "review_time": datetime.now().isoformat(),
            "analysis_result": analysis_result,
            "report_version": "1.0"
        }
        
        return json.dumps(report_data, ensure_ascii=False, indent=2)
    
    def generate_summary_stats(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
        """
        生成统计摘要
        
        Args:
            analysis_result: 分析结果
            
        Returns:
            统计信息
        """
        overall_score = analysis_result.get('overall_score', 0)
        risks = analysis_result.get('risks', [])
        recommendations = analysis_result.get('recommendations', [])
        details = analysis_result.get('details', {})
        
        # 计算各类型评分
        type_scores = {}
        for review_type, result in details.items():
            if isinstance(result, dict) and 'score' in result:
                type_scores[review_type] = result['score']
        
        return {
            "overall_score": overall_score,
            "risk_level": self._get_risk_level(overall_score),
            "total_risks": len(risks),
            "total_recommendations": len(recommendations),
            "review_types_count": len(details),
            "type_scores": type_scores,
            "average_type_score": sum(type_scores.values()) / len(type_scores) if type_scores else 0
        }
    
    def _get_risk_level(self, score: int) -> str:
        """根据评分获取风险等级"""
        if score >= 80:
            return "低风险"
        elif score >= 60:
            return "中等风险"
        else:
            return "高风险"
